<template>
  <div class="app-container">
    <el-form
      v-if="showDetail"
      ref="configForm"
      :model="configForm"
      label-width="180px">
      <el-row>
        <el-form-item>
          <el-button
            type="primary"
            size="small"
            @click="addPassage">
            增加通道
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="addBackupPassage">
            增加备用通道
          </el-button>
        </el-form-item>
      </el-row>
      <el-row
        v-for="(config, index) in configForm.form"
        :key="index"
        :gutter="20">
        <el-col :span="10">
          <el-form-item
            :label="config.is_backup_channels == 1 ? '备用通道': '第' + (index + 1) + '通道：'"
            :prop="'form.' + index + '.product_id'"
            :rules="{
              required: true,
              message: '请选择通道',
              trigger: 'blur',
            }">
            <resource-select
              v-model="config.product_id"
              :action="productGetList"
              valueKey="id"
              :searchDefault="searchDefault"
              labelKey="product_search_field"></resource-select>
          </el-form-item>
        </el-col>
        <el-col :span="4" v-if="config.is_backup_channels == 0">
          <el-form-item
            label="权重"
            :prop="'form.' + index + '.weight'"
            :rules="{
              required: true,
              message: '请设置权重',
              trigger: 'blur',
            }"
            label-width="60px">
            <el-input-number
              style="width: 100%"
              v-model="config.weight"
              :min="0"
              :max="100"
              :precision="0"
              :step="1"
              :controls="false"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item
            label="单价"
            :prop="'form.' + index + '.unit_price'"
            :rules="{
              required: true,
              message: '请设置单价',
              trigger: 'blur',
            }"
            label-width="60px">
            <el-input-number
              style="width: 100%"
              v-model="config.unit_price"
              :min="0"
              :max="100"
              :precision="4"
              :step="0.001"
              :controls="false"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label-width="0px">
            <el-button
              v-if="index > 0"
              type="danger"
              size="small"
              @click="removePassage(index)">
              移除通道
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>
import { getUserProductDetail, setProductChannel } from '@/api/user';
import { getList as productGetList } from '@/api/product';
import ResourceSelect from '@/components/ResourceSelect/index';
export default {
  name: 'setting',
  components: {
    ResourceSelect,
  },
  data() {
    return {
      userProductDetail: null,
      configForm: {
        user_product_id: this.userProductId,
        form: [
          this.initChannel(0)
        ],
      },
      searchDefault: {},
      productGetList,
      showDetail: false,
    };
  },
  props: {
    userProductId: {
      type: [String, Number],
      default: 0,
    },
  },
  watch: {
    userProductId: {
      handler(value) {
        this.getDetail(value);
      },
      immediate: true,
    },
  },
  methods: {
    initChannel(type){
      return JSON.parse(JSON.stringify(
        {
          product_id: '',
          unit_price: 0,
          weight: 0,
          is_backup_channels: type
        }
      ))
    },
    async getDetail(value) {
      let res = await getUserProductDetail({ id: value });
      this.$set(this, 'userProductDetail', res.data);
      this.$set(this, 'searchDefault', {
        category_id: res.data.product_category_id,
      });
      if( res.data.user_product_channels ){
        this.$set( this.configForm, 'form', res.data.user_product_channels )
      }
      this.$set(this, 'showDetail', true);
    },
    addPassage() {
      if( !this.checkBackUpPassage() ){
        this.configForm.form.push(this.initChannel(0));
      } else {
        this.configForm.form.splice(-1, 0, this.initChannel(0));
      }
    },
    addBackupPassage(){
      if( !this.checkBackUpPassage() ){
        this.configForm.form.push(this.initChannel(1)); 
      }
    },
    checkBackUpPassage(){
      let backupChannel = this.configForm.form.filter( el => el.is_backup_channels == 1 )
      return backupChannel.length == 1 ? true: false
    },
    removePassage(index) {
      this.configForm.form.splice(index, 1);
    },
    handleSubmit(){
      this.$refs.configForm.validate(valid => {
        if (valid) {
          let sumWithInitial = 0
          this.configForm.form.forEach(item => {
            if (item.is_backup_channels == 0) {
              sumWithInitial += item.weight;
            }
          });
          if (sumWithInitial != 100) {
            this.$message.error('所有通道权重总计必须为100');
          } else {
            this.$emit('update:loadingButton', ['submit']);
            setProductChannel(this.configForm).then(()=>{
              this.$emit('update:loadingButton', []);
              this.$emit('update:visible', false);
            }).catch(()=>{
              this.$emit('update:loadingButton', []);
            })
          }
        }
      });
    }
  },
};
</script>